package cn.cf.kxx;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.cf.kxx.adapter.GridExeAdapter;
import cn.cf.kxx.adapter.GridExeGroupAdapter;
import cn.cf.kxx.adapter.GridGroupAdapter;
import cn.cf.kxx.adapter.GridGroupValveAdapter;
import cn.cf.kxx.data.DataSharedPreferences;
import cn.cf.kxx.fram.OnActivityInteractionListener;
import cn.cf.kxx.fram.OnFragmentInteractionListener;
import cn.cf.kxx.model.ExePlan;
import cn.cf.kxx.model.Group;
import cn.cf.kxx.model.Valve;
import cn.cf.kxx.model.dev.Hold;
import cn.cf.kxx.service.IMyAidlCallBack;
import cn.cf.kxx.service.ISerialAidlInterface;
import cn.cf.kxx.tools.Tools;

public class ExePlanActivity extends Fragment implements View.OnClickListener, OnFragmentInteractionListener, AdapterView.OnItemClickListener {

    @Override
    public void onRefrashString(String type) {
    }

    @Override
    public void onRefrashValve(int status) {

    }
    @Override
    public void onRefrashValues(Object obj) {

    }
    Button save_exeplan;
    Button goHome;
    View contentView;

    GridView exeplans,group_list;

    TextView info;

    DataSharedPreferences sharedPreferences;

    //选中的
    List<Group> exePlanGroup = new ArrayList<>();

    //
    Map<String, Group> maps;
    Map<String, Group> selectMaps;

    GridExeGroupAdapter gridGroupAdapter;

    GridExeAdapter gridExeAdapter;

    String devBh;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sharedPreferences = DataSharedPreferences.getInstance();
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            devBh = bundle.getString("devBh");
        }
    }

    public static ExePlanActivity newInstance(Bundle args) {
        ExePlanActivity fragment = new ExePlanActivity();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if(contentView == null){
            contentView = inflater.inflate(R.layout.activity_exe_plan,container,false);
            initView();
        }else{
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
        }
        return contentView;
    }

    EditText hour,minute,second,year,month,day;

    ExePlan exePlan = null;

    private void initView(){
        exeplans = contentView.findViewById(R.id.exeplans);
        info = contentView.findViewById(R.id.info);
        goHome = contentView.findViewById(R.id.goHome);
        goHome.setOnClickListener(this);
        save_exeplan = contentView.findViewById(R.id.save_exeplan);
        save_exeplan.setOnClickListener(this);
        group_list = contentView.findViewById(R.id.group_list);

        hour = contentView.findViewById(R.id.hour);
        minute = contentView.findViewById(R.id.minute);
        second = contentView.findViewById(R.id.second);
        year = contentView.findViewById(R.id.year);
        month = contentView.findViewById(R.id.month);
        day = contentView.findViewById(R.id.day);


        String exeText = sharedPreferences.getExePlan(getActivity());


        if(TextUtils.isEmpty(exeText)){
            exePlan = new ExePlan();
            exePlan.setDevBh(devBh);
            exePlan.setBh("1");
            exePlan.setName("设备同步");
            //2023-06-26 18:37

            exePlan.setValOpenTime("2021-01-01 00:00");
            //状态  0正常  1执行  2结束  3异常  4关闭  5暂停  6恢复

            exePlan.setValId("");
            exePlan.setCreateDate(new Date());
            exePlan.setStatus(0);
            sharedPreferences.addExePlan(getActivity(),Tools.gson.toJson(exePlan));
        }else{
            exePlan = Tools.gson.fromJson(exeText,ExePlan.class);
            exePlan.setValOpenTime("2021-01-01 00:00");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            LocalDateTime dateTime = LocalDateTime.parse(exePlan.getValOpenTime(), formatter);
            year.setText(String.valueOf(dateTime.getYear()));
            month.setText(String.valueOf(dateTime.getMonthValue()));
            day.setText(String.valueOf(dateTime.getDayOfMonth()));
            hour.setText(String.valueOf(dateTime.getHour()));
            minute.setText(String.valueOf(dateTime.getMinute()));
            second.setText("00");
        }
        //得到所有组的map
        maps = getAllGroups().stream().collect(Collectors.toMap(group -> String.valueOf(group.getZbh()), Function.identity()));
        //选中的map
        selectMaps = new HashMap<>();
        //得到所有选中的组
        if(exePlan.getValId().contains(",")){
            String[] ids = exePlan.getValId().split(",");
            for(int i = 0;i < ids.length;i++){
                selectMaps.put(ids[i],maps.get(ids[i]));
                exePlanGroup.add(maps.get(ids[i]));
            }
        }

        //刷新左侧列表
        gridExeAdapter = new GridExeAdapter(getActivity(),exePlanGroup);
        exeplans.setAdapter(gridExeAdapter);
        exeplans.setOnItemClickListener((parent, view, position, id) -> {
            //左侧点击触发
            Group group = (Group) gridExeAdapter.getItem(position);
            selectMaps.remove(String.valueOf(group.getZbh()));
            gridExeAdapter.remove(position);//ui删除选中
            if(gridExeAdapter.getCount() == 0){
                info.setVisibility(View.VISIBLE);
                exeplans.setVisibility(View.GONE);
            }
            gridGroupAdapter.setGroups(getWxzGroups());
        });

        //刷新右侧列表左侧没选中，则显示文字
        if(exePlanGroup.size() == 0){
            info.setVisibility(View.VISIBLE);
            exeplans.setVisibility(View.GONE);
        }else{
            info.setVisibility(View.GONE);
            exeplans.setVisibility(View.VISIBLE);
        }

        //刷新右侧，只显示没有选中的
        gridGroupAdapter = new GridExeGroupAdapter(getActivity(),getWxzGroups());
        group_list.setAdapter(gridGroupAdapter);
        group_list.setOnItemClickListener(this);
    }

    /**
     * 刷新右侧数据
     */
    private ArrayList<Group> getWxzGroups(){
        //缓存读出来
        ArrayList<Group> groups = getAllGroups();
        ArrayList<Group> groupsValue = new ArrayList<>();
        for(int i = 0;i < groups.size();i++){
            if(!selectMaps.containsKey(String.valueOf(groups.get(i).getZbh()))){
                groupsValue.add(groups.get(i));
            }
        }
        return groupsValue;
    }



    ArrayList<Group> groups = null;

    private ArrayList<Group> getAllGroups(){
        if(groups != null){
            return groups;
        }
        //缓存读出来
        String content = sharedPreferences.getGroup(getActivity());
        Type listType = new TypeToken<ArrayList<Group>>() {}.getType();
        groups = Tools.gson.fromJson(content, listType);
        if(groups.size() == 0){
            Group group;
            for(int i = 1;i < 51;i++){
                group = new Group();
//                group.setParentId(device.getParentId());
                group.setDevBh(devBh);
                group.setZbh((short) i);
                group.setName("默认" + i);
                group.setRemarks("无");
                group.setStatus(0);
                group.setContent("");
                group.setCreateDate(new Date());
                groups.add(group);
            }
            sharedPreferences.addGroup(getActivity(), Tools.gson.toJson(groups));
        }
        return groups;
    }

    OnActivityInteractionListener onActivityInteractionListener;
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        onActivityInteractionListener = (OnActivityInteractionListener) context;
    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.goHome){
            onActivityInteractionListener.bakeFragment();
        }else if(view.getId() == R.id.save_exeplan){
//            startActivity(new Intent(this,IrrigateActivity.class));
            String yearTxt = year.getText().toString();
            String monthTxt = month.getText().toString();
            String dayTxt =  day.getText().toString();
            String hourTxt = hour.getText().toString();
            String minuteTxt =  minute.getText().toString();

            String joinedValues = String.join(",", selectMaps.values().stream()
                    .map(group -> String.valueOf(group.getZbh()))
                    .collect(Collectors.toList()));

            exePlan.setValOpenTime(yearTxt+"-"+monthTxt+"-"+dayTxt+" "+hourTxt+":"+minuteTxt);
            exePlan.setValId(joinedValues);
            sharedPreferences.addExePlan(getActivity(),Tools.gson.toJson(exePlan));
            Toast.makeText(getActivity(),"任务保存成功",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //右侧点击触发
        Group group = (Group) gridGroupAdapter.getItem(position);
        gridGroupAdapter.remove(position);//在右侧删除
        //ui加入选中
        gridExeAdapter.add(group);
        //记录
        selectMaps.put(String.valueOf(group.getZbh()),group);

        info.setVisibility(View.GONE);
        exeplans.setVisibility(View.VISIBLE);
    }
}